#!/opt/homebrew/bin/bash

# 从环境变量读取服务器信息

SERVER_USER=${SERVER_USER:-"root"}
REMOTE_DIR="/data/java/"

# 定义键值对映射
declare -A JAR_MAP=(
    ["portal"]="portal"
    ["admin"]="admin"
)
declare -A ENV_MAP=(
    ["dev_meta"]="http://172.31.69.57:7071"
    ["prod_meta"]="http://47.113.124.224:7071"
    ["dev_ip"]="59.110.91.205"
    ["prod_ip"]="47.113.124.224"
)

# 检查是否提供了正确的参数
if [ "$#" -ne 3 ] && [ "$1" != "all" ]; then
    echo "Usage: $0 <key> <version>"
    exit 1
fi

# 获取键值
KEY="$1"
VERSION="$2"
ENVIRONMENT="$3"
cmd="$4"
env_ip_key="${ENVIRONMENT}_ip"
SERVER_IP=${SERVER_IP:-${ENV_MAP[$env_ip_key]}}

start_jar() {
    local key="$1"
    # 杀死已存在的进程
    kill_existing_process "$key"
    # 启动新的进程
    if [[ "$cmd" != "stop" ]]; then
      start_new_process "$key"
    fi
}

kill_existing_process() {
    local key="$1"
    local remote_jar_path="${REMOTE_DIR}drama-$key-.*-SNAPSHOT.jar"
    # 构造正则表达式
    local regex=".*$remote_jar_path.*$ENVIRONMENT.*"

    # 查找并杀死已存在的进程
    local pid=$(ssh "${SERVER_USER}@${SERVER_IP}" "pgrep -f $regex")
    if [ -n "$pid" ]; then
        ssh "${SERVER_USER}@${SERVER_IP}" "kill -11 $pid"
        echo "停止服务成功: $key version:$VERSION ENV:$ENVIRONMENT (PID: $pid)"
    else
        echo "服务不存在: $key version:$VERSION ENV:$ENVIRONMENT"
    fi
}

start_new_process() {
    local key="$1"
    local env_key="${ENVIRONMENT}_meta"
    local remote_jar_path="${REMOTE_DIR}drama-$key-$VERSION-SNAPSHOT.jar"
    # 启动新的进程
    ssh "${SERVER_USER}@${SERVER_IP}" "nohup java -Dapollo.meta=${ENV_MAP[$env_key]} -Denv=${ENVIRONMENT} -jar $remote_jar_path  --spring.profiles.active=$ENVIRONMENT > /data/java/log/$key-$ENVIRONMENT.txt 2>&1 &"
    echo "启动成功: 服务：$key version:$VERSION ENV:$ENVIRONMENT,启动命令[nohup java -Dapollo.meta=${ENV_MAP[$env_key]} -Denv=${ENVIRONMENT} -jar $remote_jar_path  --spring.profiles.active=$ENVIRONMENT > /data/java/log/$key-$ENVIRONMENT.txt 2>&1 &]"

}

if [ "$KEY" = "all" ]; then
    for key in "${!JAR_MAP[@]}"; do
        if ! start_jar "$key"; then
            echo "Start failed for key: $key"
        fi
    done
else
    if [[ -z "${JAR_MAP[$KEY]}" ]]; then
        echo "Error: Key '$KEY' not found in the [ portal,admin ]."
        exit 1
    fi

    if ! start_jar "$KEY"; then
        echo "Start failed for key: $KEY"
        exit 1
    fi
fi
